
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <shellapi.h>
#include <process.h>

#if defined( _MSC_VER )
	#include <crtdbg.h>
	#define WIN32_LEAN_AND_MEAN
	#include <windows.h>
	_CrtMemState startMemState;
	_CrtMemState endMemState;
#endif

using namespace std;

vector<string> split(const string& s); 


int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	string command; 
	string params;

	// parse the command line (dodgy code - my C++ needs work)

	string item;
	stringstream ss(lpCmdLine);
	ss >> item;
	if (item[0] == '"')
	{
		if (item[item.length() - 1]=='"') 
		{
			command = (item.substr(1, item.length()-2));
		} 
		else 
		{
			string restOfItem;
			getline(ss, restOfItem, '"');
			command = (item.substr(1) + restOfItem);
		}
		params = string(lpCmdLine).substr(command.length() + 2);
	}
	else
	{
		command = item;
		params = string(lpCmdLine).substr(command.length());
	}

	// trim leading white space 
	while (params[0]==' ') 
	{
		params = params.substr(1, params.length() - 1);
	}

	// remove outer quotes if needeed
	if (params[0]=='"') 
	{
		params = params.substr(1, params.length() - 2);
	} 

	//string mesg;
	//mesg = "Admin exec command: " + command;
	//MessageBox(NULL, mesg.data(), "Admin Exec", (MB_OK | MB_ICONINFORMATION | MB_SERVICE_NOTIFICATION));
    //mesg = "Admin exec params: " + params;
	//MessageBox(NULL, mesg.data(), "Admin Exec", (MB_OK | MB_ICONINFORMATION | MB_SERVICE_NOTIFICATION));

    SHELLEXECUTEINFO sinfo;
	memset(&sinfo, 0, sizeof(SHELLEXECUTEINFO));
	sinfo.cbSize       = sizeof(SHELLEXECUTEINFO);
	sinfo.fMask        = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_NOCLOSEPROCESS;
	sinfo.hwnd         = NULL;
	sinfo.lpFile       = command.data();
	sinfo.lpParameters = params.data();
	sinfo.lpVerb       = "runas"; // <<-- this is what makes a UAC prompt show up
	sinfo.nShow        = SW_SHOWMAXIMIZED;

	BOOL result = ShellExecuteEx(&sinfo);
	WaitForSingleObject(sinfo.hProcess, 60000);

	return (result == TRUE ? 0 : 1);
}
